#!/usr/bin/python3
# coding: utf-8
# file: logging_.py
# 2018-06-12
import logging, os, time
from logging.handlers import TimedRotatingFileHandler

DEBUG = True
LOG_LEVEL = logging.DEBUG if DEBUG else logging.INFO


def create_logger(filename='log', when='M', interval=1, backupCount=10):
	'''创建一个记录日志的实例, 并添加控制台和文件句柄同时写入, 写入文件时还可以定时切割日志文件写入'''
	logger = logging.getLogger()
	logger.handlers.clear()
	logger.setLevel(LOG_LEVEL)

	# fh = logging.FileHandler(logfile, mode='w') 	# 输入文件
	fh = TimedRotatingFileHandler(filename=filename, when=when, interval=interval, backupCount=backupCount) # 间隔输入不同文件
	ch = logging.StreamHandler() 					# 输入控制台

	formatter = logging.Formatter("[%(asctime)s] - [%(filename)s] [line:%(lineno)d] - [%(levelname)s]: %(message)s")
	fh.setFormatter(formatter)
	ch.setFormatter(formatter)

	logger.addHandler(fh)
	logger.addHandler(ch)

	return logger

# logger = create_logger()


# logger.removeHandler(fh)p = Pool(p_num)


def test_func(i):
	file = f'logs/log_{i}.txt'
	logger = create_logger(filename=file)
	n = 30
	while n > 0:
		logger.debug(f'[test_{i}] this is a logger debug message: [{n}]')
		# logger.info(f'[test_{i}] this is a logger info message')
		# logger.warning('this is a logger warning message')
		# logger.error('this is a logger error message')
		# logger.critical('this is a logger critical message')
		n -= 1


if __name__ == '__main__':

	from multiprocessing import Pool
	p = Pool(10)
	# 多进程执行脚本
	for i in range(10):
		p.apply_async(test_func, args=(i,))

	p.close()
	p.join()